package com.fans.admin.quartz.job;

import org.quartz.spi.TriggerFiredBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

/**
 * Autowire Quartz Jobs with Spring context dependencies
 * 
 * @author fanhaohao
 *
 */
public class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

	private Logger logger = LoggerFactory.getLogger(AutowiringSpringBeanJobFactory.class);
	
	private transient AutowireCapableBeanFactory beanFactory;
	
	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		// TODO Auto-generated method stub
		beanFactory = context.getAutowireCapableBeanFactory();
	}

	@Override
	protected Object createJobInstance(TriggerFiredBundle bundle)
			throws Exception {
		// TODO Auto-generated method stub
		final Object job = super.createJobInstance(bundle);
	    beanFactory.autowireBean(job);
		logger.info("==========================AutowiringSpringBeanJobFactory===========================");
	    return job;
	}
}
